﻿namespace DimensionsHelper.Client.WinUi.Services;

public class FileService : IFileService
{
    public bool Exists(string fileName) => File.Exists(fileName);


    public string Read(string fileName, Encoding encoding) =>
        File.Exists(fileName) ? File.ReadAllText(fileName, encoding) : string.Empty;


    public T? Read<T>(string fileName) => File.Exists(fileName) ? JsonHelper.ReadJson<T>(fileName) : default;


    public T? Read<T>(string folderPath, string fileName)
    {
        string? path = Path.Combine(folderPath, fileName);
        return File.Exists(path) ? JsonHelper.ReadJson<T>(path) : default;
    }


    public T? Read<T>(string fileName, JsonTypeInfo<T> jsonTypeInfo) => JsonHelper.ReadJson(fileName, jsonTypeInfo);


    public T? Deserialize<T>(string content, JsonTypeInfo<T> jsonTypeInfo) =>
        JsonSerializer.Deserialize(content, jsonTypeInfo);


    public void Save(string fileName, string content, Encoding encoding) =>
        File.WriteAllText(fileName, content, encoding);


    public void Save<T>(string fileName, T content) =>
        JsonHelper.WriteJson(content, fileName, ServiceJsonContext.Default);


    public void Save<T>(string fileName, JsonTypeInfo<T> jsonTypeInfo, T content) =>
        JsonHelper.WriteJson(content, jsonTypeInfo, fileName);


    public void Save<T>(string folderPath, string fileName, T content)
    {
        if (content is null)
        {
            return;
        }

        if (!Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath);
        }

        JsonHelper.WriteJson(content, Path.Combine(folderPath, fileName));
    }

    public void Delete(string folderPath, string fileName)
    {
        if (!string.IsNullOrEmpty(fileName) && File.Exists(Path.Combine(folderPath, fileName)))
        {
            File.Delete(Path.Combine(folderPath, fileName));
        }
    }
}